<template>
    <div class="pkInvitePage">
        <div class="pkInviteBox">

            <!--头像名称-->
            <div class="pkInviteHead" v-if="isRoomOwner">
                <div class="wo invite">
                    <div class="avatar">
                        <img :src='userinfo.headimgurl' alt="">
                    </div>
                    <span class="name">{{ userinfo.nickname }}</span>
                </div>
                <div class="vs"></div>
                <div class="ta">
                    <div class="avatar">
                        <img :src='robotHeader' alt="" v-model='robotHeader'>
                    </div>
                    <span class="name" v-model='robotName'>{{ robotName }}</span>
                </div>

            </div>
            <div class="pkInviteHead" v-if="!isRoomOwner">
                <div class="wo">
                    <div class="avatar">
                        <img :src='userinfo.headimgurl' alt="">
                    </div>
                    <span class="name">{{ userinfo.nickname }}</span>
                </div>
                <div class="vs"></div>
                <div class="ta invite">
                    <div class="avatar">
                        <img :src='robotHeader' alt="" v-model='robotHeader'>
                    </div>
                    <span class="name" v-model='robotName'>{{ robotName }}</span>
                </div>
            </div>

            <div class="pkInviteBody">

                <!--等待中-->
                <div class="wait" id="wait" v-if="isRoomOwner">

                    <!--倒计时-->
                    <div class="countdownBox">
                        <div class="circle"></div>
                        <div class="body">
                            <p>寻找小伙伴</p>
                            <!-- <div class="dotted">......</div> -->
                            <div class="time">
                                <span class="num"></span>
                            </div>
                        </div>
                    </div>

                    <div class="giveup" @click="giveUp">放 弃</div>

                </div>


                <!--好友加入-->
                <div id="match" class="match">

                    <!--准备开始-->
                    <div class="matchBox">
                        <div class="head">
                            <p><span>PK</span>共<span>5</span>道题</p>
                            <p>得分高者获胜</p>
                        </div>
                        <div class="body">
                            <div class="ready"></div>
                            <div class="start"></div>
                        </div>
                    </div>

                </div>


                <!--超时-->
                <div id="timeout" class="timeout">
                    <div class="time">00:00</div>
                    <p>邀请已超时</p>
                    <div class="btns">
                        <div class="invite" @click="pkInvite">邀请好友</div>
                        <div class="random" @click="pkRandom">随机匹配</div>
                        <div class="back" @click="goHome">返回首页</div>
                    </div>
                </div>


                <!--来晚了，对战中-->
                <div id="late" class="late">
                    <div class="icon"></div>
                    <p>来晚了，对战中</p>
                    <div class="btns">
                        <div class="invite" @click="pkInvite">邀请好友</div>
                        <div class="random" @click="pkRandom">随机匹配</div>
                        <div class="back" @click="goHome">返回首页</div>
                    </div>
                </div>

            </div>


        </div>
        <!--放弃浮层-->
        <div id="modalGiveUp" aria-hidden="true" class="modal fade in" role="dialog">
            <div class="giveUpBox">
                <div class="body">
                    <h3>放弃邀请</h3>
                    <p>确定要关闭邀请吗？</p>
                    <div>
                        <span class="cancel" data-dismiss="modal">取 消</span>
                        <span class="ok" @click="giveUpConfirm">确 定</span>
                    </div>
                </div>
                <div class="close" data-dismiss="modal"></div>
            </div>
        </div>
        <!--pk邀请分享浮层-->
        <div id="pkInviteShare" aria-hidden="true" class="modal fade in" role="dialog">
            <div class="inviteShareBox" data-dismiss="modal">
                <img :src="appConfig.staticUrl+'answerpk/img/pk_invite_share.png'" alt="">
            </div>
        </div>
    </div>
</template>

<script>
import appConfig from "../config/appConfig";

export default {
    name: 'pk_invite',
    data() {
        return {
            uid: this.userHelper.getInfo('user_cert'),
            robotHeader: appConfig.staticUrl + "answerpk/img/avatar.jpg",
            robotName: '等待好友加入',
            countDownObj: '',
            isrobot: '',
            userinfo: {},
            roomID: '',                     // 房间 ID
            isRoomOwner: false,             // 是否房主
            inviteTime: 0,                  // 邀请时间
            isTimeout: false,               // 是否超时
            countDownSeconds: 60 * 1000,    // 倒计时（s）
        }

    },
    created: function () {
        this.userinfo = this.userHelper.getInfo('');
        this.userinfo.headimgurl = this.userinfo.headimgurl ? this.userinfo.headimgurl : appConfig.staticUrl + 'answerpk/img/avatar.jpg';

        // this.inviteInit();
    },

    mounted: function () {
        // this.inviteReset();
    },
    activated: function () {
        this.inviteInit();
        this.inviteReset();
    },
    methods: {
        // 邀请参数初始化
        inviteInit: function () {
            // 房间 ID
            this.roomID = this.commonHelper.query('room');

            // 没有房间 ID 回到首页
            if (!this.roomID) {
                this.$emit('handle', {name: 'pkIndex'});
                return false;
            }

            // 是否房主
            this.isRoomOwner = this.uid === parseInt(this.commonHelper.query('roomOwner'));

            // 邀请时间
            this.inviteTime = this.commonHelper.query('time');

            // 是否超时
            this.isTimeout = (new Date).getTime() - parseInt(this.inviteTime) > this.countDownSeconds;
        },

        // 邀请重置
        inviteReset: function () {
            // 超时提示
            if (this.isTimeout) {
                this.timeout();
                return false;
            }

            // 是房主 且 未超时 显示分享提示及倒计时
            if (this.isRoomOwner) {
                $("#pkInviteShare").modal();

                // 自动隐藏分享提示
                setTimeout(function () {
                    $("#pkInviteShare").modal('hide');
                }, 4000)

                // 倒计时开始
                this.countDown();
            }

            // 发送 socket 消息
            this.onopen();

            // 微信分享
            this.wxShare();
        },

        // 邀请 PK
        pkInvite: function () {
            this.$router.push({
                path: 'index',
                query: {
                    room: this.commonHelper.generateRoomID(),
                    roomOwner: this.uid,
                    time: (new Date).getTime(),
                }
            }).then(() => {
                this.inviteInit();
                this.inviteReset();
            });
        },

        // 随机 PK
        pkRandom: function () {
            this.$emit('handle', {name: 'pkRandom'});
        },

        // 回到首页
        goHome: function () {
            location.href = appConfig.onLineApiDomain + '/index';
        },

        // 放弃邀请
        giveUp: function () {
            $("#modalGiveUp").modal({"backdrop": "static"});
        },

        // 确认放弃
        giveUpConfirm: function () {
            this.state = 1;
            this.quitRoom();
            this.goHome();
        },

        // 对战中
        late: function () {
            this.robotName = '';
            $("#wait").hide();
            $("#match").hide();
            $("#timeout").hide();
            setTimeout(function () {
                $("#late").fadeIn();
            }, 10);
        },

        // 倒计时
        countDown: function () {
            const _this = this;
            this.robotName = '等待好友加入';
            $("#timeout").hide();
            $("#match").hide();
            $("#late").hide();
            setTimeout(function () {
                $("#wait").fadeIn();
                $(".countdownBox .num").countdown(Date.now() + _this.countDownSeconds, function (event) {
                    $(this).html(event.strftime('%M:%S'));
                }).on('finish.countdown', function () {
                    _this.state = 0;
                    _this.quitRoom();
                    _this.timeout();
                });
            }, 10);
        },

        // 超时
        timeout: function () {
            this.robotName = '';
            $("#wait").hide();
            $("#match").hide();
            $("#late").hide();
            setTimeout(function () {
                $("#timeout").fadeIn();
            }, 10);
        },

        // 邀请成功
        inviteSuccess: function () {
            const _this = this;
            $("#wait").hide();
            $("#timeout").hide();
            $("#late").hide();
            $("#match").fadeIn(function () {
                $(this).find(".matchBox").toggleClass("active", true);

                setTimeout(function () {
                    _this.$emit('handle', {name: 'pk'})
                }, 2000);
            });
        },

        // 进入答题
        startPk: function () {
            if (this.isRoomOwner) {
                this.socket.sendMessage({
                    'gameType': 'invite_std',
                    'type': 'joinRoom',
                    'roomId': this.roomID,
                    'userType': this.isRoomOwner ? 0 : 1,
                    'uid': this.uid,
                    'nickname': this.userinfo.nickname,
                    'image': this.userinfo.headimgurl,
                });
            } else {
                this.socket.sendMessage({
                    'gameType': 'invite_std',
                    'type': 'getInviteStatus',
                    'roomId': this.roomID,
                    'uid': this.uid,
                });
            }
        },

        // 退出房间
        quitRoom: function () {
            this.socket.sendMessage({
                'gameType': 'invite_std',
                'type': 'quitRoom',
                'uid': this.uid,
                'roomId': this.roomID,
            });
        },

        // 真人 PK
        goRoomWithPerson: function (gameType) {
            this.socket.sendMessage({
                'gameType': gameType,
                'type': 'joinRoom',
                'roomId': this.roomID,
                'userType': this.isRoomOwner ? 0 : 1,
                'uid': this.uid,
                'nickname': this.userinfo.nickname,
                'image': this.userinfo.headimgurl,
            });
        },

        onopen: function () {
            this.startPk();
        },

        onmessage: function (e) {
            const _this = this;
            const rs = JSON.parse(e.data);
            console.log('回调', rs);

            if (rs.code == 0 && rs.type == 'quitMatchSuccess') {
                //退出匹配
                _this.goRoomWithSingle();
            }
            if (rs.code == 2 && rs.type == 'joinRoomComplete') {
                this.startPk('invite_std');
            }
            if (rs.code == 1 && rs.type == 'quitSuccess') {
                if (_this.state == 1) {
                    _this.$emit('handle', {name: 'pkIndex'});
                }
                //退出房间成功
                // _this.countDownObj.countdown('stop');

            }
            if (rs.code == 0 && rs.type == 'getInviteStatusSuccess') {

                var datanum = 0;
                for (var i in rs.data.userData) {
                    datanum++;
                }
                console.log(rs.data.userData);
                if (datanum == 2) {
                    //对战中
                    _this.late();
                } else {
                    //邀请过期
                    _this.timeout();
                }

            }
            if (rs.code == 1 && rs.type == 'getInviteStatusSuccess') {
                //邀请未过期
                var datas = rs;

                _this.isrobot = 0;

                for (var i in rs.userData) {
                    if (rs.userData[i].uid != _this.uid) {
                        _this.robotHeader = rs.userData[i].headurl;
                        _this.robotName = rs.userData[i].nickname;
                        datas.robotHeader = rs.userData[i].headurl;
                        datas.robotName = rs.userData[i].nickname;
                        datas.robotuserType = rs.userData[i].userType;

                    } else {
                        datas.myuserType = rs.userData[i].userType ? rs.userData[i].userType : 0;
                    }
                }
                datas.roomId = _this.roomId;
                datas.gameType = 'invite_std';
                datas.isrobot = 0;
                console.log('shuju', datas);
                localStorage.setItem('pkuserinfo', JSON.stringify(datas));


                //that.showInvite();*/
                // _this.countDownObj.countdown('stop');
                _this.goRoomWithPerson('invite_std');
            }
            if (rs.code == 4 && rs.type == 'getInviteStatusSuccess') {
                //掉线返回

                _this.goRoomWithPerson('invite_std');
            }
            if (rs.code == 2 && rs.type == 'getInviteStatusSuccess') {
                //对战中
                _this.late();
            }

            if (rs.code == 3 && rs.type == 'joinRoomByPK') {

                //_this.startPk('pk_std');

            }
            if (rs.code == 2 && rs.type == 'joinRoomWithPerson') {
                var datas = {};
                $("#wait").hide();
                _this.isrobot = 0;

                for (var i in rs.userData) {
                    if (rs.userData[i].uid != _this.uid) {
                        _this.robotHeader = rs.userData[i].headurl;
                        _this.robotName = rs.userData[i].nickname;
                        datas.robotHeader = rs.userData[i].headurl;
                        datas.robotName = rs.userData[i].nickname;
                        datas.robotuserType = rs.userData[i].userType;

                    } else {
                        datas.myuserType = rs.userData[i].userType ? rs.userData[i].userType : 0;
                    }
                }

                datas.gameType = 'invite_std';
                datas.isrobot = 0;
                //datas.bot =123;
                datas.roomId = _this.roomID;
                console.log('shuju', datas);
                localStorage.setItem('pkuserinfo', JSON.stringify(datas));
                localStorage.setItem('roomID', '');
                var list = localStorage.getItem('pkuserinfo');
                console.log(list);
                //if(list){
                setTimeout(function () {
                    _this.inviteSuccess();
                }, 1000);

                //}
            }
            if (rs.code == 4 && rs.type == 'joinRoomAgain') {
                //掉线返回房间
                for (var i in rs.userData) {
                    if (rs.userData[i].uid != _this.uid) {
                        _this.robotHeader = rs.userData[i].headurl;
                        _this.robotName = rs.userData[i].nickname;
                        break;
                    }
                }
                //_this.againAnswer('invite_std');
            }
        },

        // 微信分享
        wxShare: function () {
            const url = appConfig.baseUrl + 'answerpk/index?room=' + this.roomID + '&roomOwner=' + this.uid + '&time=' + (new Date).getTime();

            console.log(url);

            this.wxHelper.init({
                types: ['share'],
                callback: (status) => {
                    if (status) {
                        this.wxHelper.shareMessage({
                            title: '我正在参加“党史天天学”知识竞答双人对战，快来挑战我吧！', // 分享标题
                            desc: '', // '我正在参加“党史天天学”知识竞答双人对战，快来挑战我吧！', // 分享描述
                            link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: appConfig.onLineDomain + '/h5/img/wxShare.jpg', // 分享图标
                        });
                    }
                }
            });
        },
    },
}
</script>
